package com.reebake.ideal.protect.config;

import com.reebake.ideal.crypto.core.SecretKeyService;
import com.reebake.ideal.protect.core.ContentSecureService;
import com.reebake.ideal.protect.core.SignatureService;
import com.reebake.ideal.protect.filter.ContentProtectFilter;
import com.reebake.ideal.protect.filter.SignatureProtectFilter;
import com.reebake.ideal.protect.handler.DefaultContentSecureService;
import com.reebake.ideal.protect.handler.DefaultSignatureService;
import com.reebake.ideal.protect.properties.ProtectProperties;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;

@Configuration
public class ProtectConfig {
    private static final int INITIAL_ORDER = Ordered.HIGHEST_PRECEDENCE + 100;

    @Bean
    @ConditionalOnMissingBean
    public ContentSecureService contentSecureService() {
        return new DefaultContentSecureService();
    }

    @Bean
    @ConditionalOnMissingBean
    public SignatureService signatureService() {
        return new DefaultSignatureService();
    }

    @Bean
    public FilterRegistrationBean<SignatureProtectFilter> signatureProtectFilter(ProtectProperties protectProperties,
                                                                                 SignatureService signatureService, SecretKeyService secretKeyService) {
        FilterRegistrationBean<SignatureProtectFilter> registration = new FilterRegistrationBean<>();
        SignatureProtectFilter signatureProtectFilter = new SignatureProtectFilter(protectProperties, signatureService, secretKeyService);
        registration.setFilter(signatureProtectFilter);
        registration.addUrlPatterns("/*");
        registration.setBeanName(SignatureProtectFilter.class.getSimpleName());
        registration.setOrder(INITIAL_ORDER);
        return registration;
    }

    @Bean
    public FilterRegistrationBean<ContentProtectFilter> contentProtectFilter(ProtectProperties protectProperties,
                                                                             ContentSecureService contentSecureService, SecretKeyService secretKeyService) {
        FilterRegistrationBean<ContentProtectFilter> registration = new FilterRegistrationBean<>();
        ContentProtectFilter contentProtectFilter = new ContentProtectFilter(protectProperties, contentSecureService, secretKeyService);
        registration.setFilter(contentProtectFilter);
        registration.addUrlPatterns("/*");
        registration.setBeanName(SignatureProtectFilter.class.getSimpleName());
        registration.setOrder(INITIAL_ORDER + 1);
        return registration;
    }

}
